'use strict';

const bcrypt = require('bcryptjs');
const { Service } = require('egg');
const { Op } = require('sequelize');
const ModelName = 'User'
class UserService extends Service {
    /**
     * 根据分页和搜索条件获取
     */
    async getPage(where, page, pageSize) {
        return this.ctx.model[ModelName].findAndCountAll({
            attributes: { exclude: ['password'] },
            where: {
                ...where,
            },
            order:[
                // id 降序
                ['create_time','DESC']
            ],
            offset: pageSize * (page - 1),
            limit: pageSize,
        });
    }
    // 所有列表
    async allList(where) {
        return this.ctx.model[ModelName].findAll({
            where,
            order:[
                // id 降序
                ['create_time','DESC']
            ],
        });
    }
    /**
     * 代理商申请
     * @param {Object} data
     */
    async apply(data) {
      // 判断公司名称
      const userExists = await this.ctx.model[ModelName].findOne({
        attributes: ['id'],
        where: {
          company_name: data.company_name,
          role: 2
        },
      });
      if (userExists) {
        throw new Error('该公司已注册');
      }
      // 创建用户
      const newUser = await this.ctx.model[ModelName].create({
        ...data,
        role: 2,
        status: 0,
        audit_status: 0,
      });
      return newUser
    }
    async login({ email, password, role }) {
        // 根据邮箱查询用户是否存在
        const userExists = await this.ctx.model[ModelName].findOne({
          where: {
            email,
            password,
            role
          },
        })
        if (!userExists) {
          throw new Error('未注册');
        }
      console.log('userExists',userExists.dataValues)
        // if (userExists.dataValues.audit_status !== 1) {
        //   throw new Error('审核中');
        // }
        if (userExists.dataValues.status !== 1) {
          throw new Error('已禁用');
        }
        delete userExists.dataValues.password;
        return userExists
    }
    async register(data) {
        const res = await this.apply(data)
        await this.update(res.id, {
            status: 1,
            audit_status: 1
        })
        // 更新状态
        return res
    }
    async findOne(id) {
        return this.ctx.model[ModelName].findOne({
            where: {
                id,
            },
        });
    }

    /**
     * 根据id删除对应的用户
     * @param {Number} uid
     */
    async deleteUserById(id) {
        // 删除成功在删除用户
        return await this.ctx.model[ModelName].destroy({ where: { id } });
    }

    /**
     * 根据ID修改用户信息
     * @param {Number} id 用户ID
     * @param {Object} data 要修改的用户信息
     */
    async update(id, data) {
        const { username } = data;
        const andWhere = { id: { [Op.ne]: id } };
        let neenCheck = false;
        if (username) {
            neenCheck = true;
            andWhere.username = username;
        }

        if (neenCheck) {
            const userExists = await this.ctx.model[ModelName].findOne({
                attributes: ['id'],
                where: { [Op.and]: andWhere },
            });
            if (userExists) throw new Error('该账号已注册');
        }

        return await this.ctx.model[ModelName].update(data, { where: { id } });
    }
    /**
     * 更新用户密码
     * @param {Number} id 用户ID
     * @param {Object} data 新密码和旧密码
     */
    async updatePassword(id, data) {
        const user = await this.ctx.model[ModelName].findByPk(id);
        if (!user) {
            throw new Error('该账号不存在');
        }

        // 旧密码是否有误, 正确就直接修改
        const isValid = data.oldPassword === user.password
        if (!isValid) {
            throw new Error('旧密码输入不正确');
        }
        user.password = data.newPassword;
        return await user.save();
    }

}

module.exports = UserService;
